<?php


namespace common\service;


use common\model\ProjectMemberModel;
//use common\model\ProjectModel;
//use common\model\TaskWorkOrderModel;
//use common\model\TaskWorkOrderUserModel;
use common\model\UserCertModel;
use common\model\UserModel;
use support\bootstrap\Redis;
use support\SingletonTrait;
use support\ErrorCode;
use think\Exception;

class TenantService
{

    // 单例工具
    use SingletonTrait;

    /**
     * 获得租户认证信息
     * @param int $tenantId
     * @param $param
     * @return mixed
     * @throws \Exception
     */
    public function getAuthenticationInfo(int $tenantId, $param)
    {
        $param['filter'] = [
            "tenant_authentication.tenant_id" => ['-eq', $tenantId],
        ];
        $param['module_code'] = 'tenant_authentication';
        unset($param['parser_filter']);
        return teamones_request('teamones-im', 'tenant_authentication/find', ['param' => $param])['data'];
    }

    /**
     * 获得绑定的平台租户id
     * @return mixed
     * @throws \Exception
     */
    public function getPlatformTenantId()
    {
        $platformTenantConfig = teamones_request('teamones-im', 'options/find', ['param' => [
            'filter' => [
                'name' => "platform_tenant_settings",
            ],
        ]])['data'];
        if (empty($platformTenantConfig)) {
            throw new Exception("missing platform tenant config", ErrorCode::MISSING_PLATFORM_TENANT_CONFIG);
        }
        // 授权是 当前租户 授权给平台
        /**
         * 甲方为当前租户
         * 乙方为平台
         */
        $config = $platformTenantConfig['config'];
        return $config['tenant_id'];
    }


    /**
     * 查询部门成员
     * @param int $tenantId
     * @param array $param
     * @return array
     */
    public function selectDepartmentUser($tenantId, $param)
    {
        $param['param'] = rollback_parser_filter($param['param']);
        $param['param']['filter']['tenant_id'] = isset($param['param']['filter']['tenant_id']) && $param['param']['filter']['tenant_id'] > 0 ? $param['param']['filter']['tenant_id'] : $tenantId;
        if (isset($param['param']['filter']['name_or_phone'])) {
            $param['param']['filter']['name_or_phone'] = [
                "-lk", $param['param']['filter']['name_or_phone']
            ];
        }
        unset($param['parser_filter']);
        $res = teamones_request('teamones-im', 'tenant/select_department_user_department_info_merged', $param)['data'];
        if (count($res['rows']) > 0) {

            $userIdArray = array_column($res['rows'], 'user_id');
            $userService = UserService::getInstance();

            $users = $userService->getUsersByUnionIds($userIdArray, 'id,union_id,name,user_cert_id');
            $usersMap = array_column($users, null, 'union_id');

            $certIdArray = array_column($users, 'user_cert_id', 'user_cert_id');
            unset($certIdArray[0]);
            $certsMap = [];
            if (!empty($certIdArray)) {
                $certs = model(UserCertModel::class)
                    ->join("user_cert_category ON user_cert.user_cert_category_id = user_cert_category.id")
                    ->where(['user_cert.id' => ['IN', implode(',', $certIdArray)]])
                    ->field("user_cert.id,user_cert_category.name,user_cert.level")
                    ->select();
                $certsMap = array_column($certs, null, 'id');
            }

            foreach ($res['rows'] as &$row) {
                $row['saas_user'] = $usersMap[$row['user_id']] ?? null;
                $row['cert'] = null;
                if ($row['saas_user']) {
                    $row['cert'] = $certsMap[$row['saas_user']['user_cert_id']] ?? null;
                    $row['saas_user_id'] = $row['saas_user']['id'];
                }
            }
        }

        return $res;
    }

    /**
     * 查询部门成员 (非组合)
     * @param $param
     * @return array|string
     * @throws \Exception
     */
    public function selectDepartmentUserList($param)
    {
        $res = teamones_request('teamones-im', 'tenant/select_department_user', $param)['data'];
        if (empty($res['rows'])) {
            return $res;
        }
        $userIdArray = array_column($res['rows'], 'user_id');
        $users = UserService::getInstance()->getUsersByUnionIds($userIdArray, 'id,union_id,name,user_cert_id');
        $usersMap = array_column($users, null, 'union_id');
        $certIdArray = array_column($users, 'user_cert_id', 'user_cert_id');
        $certs = model(UserCertModel::class)
            ->join("user_cert_category ON user_cert.user_cert_category_id = user_cert_category.id")
            ->where(['user_cert.id' => ['IN', implode(',', $certIdArray)]])
            ->field("user_cert.id,user_cert_category.name,user_cert.level")
            ->select();
        $certsMap = array_column($certs, null, 'id');
        foreach ($res['rows'] as &$row) {
            $row['saas_user'] = $usersMap[$row['user_id']] ?? null;
            $row['cert'] = null;
            if ($row['saas_user']) {
                $row['cert'] = $certsMap[$row['saas_user']['user_cert_id']] ?? null;
                $row['saas_user_id'] = $row['saas_user']['id'];
            }
        }
        return $res;
    }

    /**
     * 查询租户用户信息
     * @param array $param
     * @return array|string
     * @throws \Exception
     */
    public function selectTenantUser(array $param)
    {
        $cacheKey = 'tenant/select_tenant_user:' . md5(serialize($param));
        $res = Redis::get($cacheKey);
        if (!empty($res)) {
            return json_decode($res, true);
        }
        $res = teamones_request('teamones-im', 'tenant/select_tenant_user', $param)['data'];
        if (count($res) > 0) {
            $userIdArray = array_column($res, 'user_id');
            $users = UserService::getInstance()->getUsersByUnionIds($userIdArray, 'id,name,avatar,phone,email,union_id');
            $usersMap = array_column($users, null, 'union_id');
            foreach ($res as &$row) {
                $row['saas_user'] = $usersMap[$row['user_id']] ?? null;
            }
        }
        APP_DEBUG && Redis::setEx($cacheKey, C('database.default_query_cache_time'), json_encode($res));
        return $res;
    }

    /**
     * 查询租户
     * @param $param
     * @return array
     */
    public function tenantSelect($param)
    {
        $tenant = teamones_request('teamones-im', 'tenant/select', $param)['data'];
        if (!empty($tenant['rows'])) {
            return $tenant['rows'];
        }
        return [];
    }

    /**
     * 查询部门成员 (非组合)
     * @param $param
     * @return array|string
     * @throws \Exception
     */
    public function selectDepartmentUserTree($param)
    {
        $param['param'] = rollback_parser_filter($param['param']);
        unset($param['parser_filter']);
        $res = teamones_request('teamones-im', 'department/department_user_tree', $param)['data'];
        if (empty($res)) {
            return $res;
        }
        $userIdArray = [];
        foreach ($res as $item) {
            foreach ($item['children'] as $child) {
                $userIdArray[$child['user']['id']] = $child['user']['id'];
            }
        }
        $users = UserService::getInstance()->getUsersByUnionIds($userIdArray, 'id,union_id,name,user_cert_id');
        $usersMap = array_column($users, null, 'union_id');
        foreach ($res as &$row) {
            foreach ($row['children'] as &$child) {
                $child['saas_user'] = $usersMap[$child['user']['id']] ?? null;
                $child['saas_user_id'] = $child['saas_user']['id'] ?? 0;
            }
        }
        return $res;
    }

    /**
     * 从租户移除
     * @param int $unionId
     * @param int $tenantId
     * @return true
     */
    public function removeTenantUser(int $unionId, int $tenantId)
    {
        $user = model(UserModel::class)->where(['union_id' => $unionId])->find();
        if (empty($user)) {
            return true;
        }

//        // 删除工单成员记录
//        $taskWorkOrderUserIdList = model(TaskWorkOrderModel::class)
//            ->join('task_work_order_user on task_work_order.id = task_work_order_user.work_order_id')
//            ->where(['task_work_order_user.user_id' => $user['id'], 'task_work_order.tenant_id' => $tenantId])
//            ->field('task_work_order_user.id')
//            ->column('id');
//        foreach (array_chunk($taskWorkOrderUserIdList, 200) as $deleteIdList) {
//            model(TaskWorkOrderUserModel::class)->where(['id' => ['IN', implode(',', $deleteIdList)]])->delete();
//        }
        // 删除项目成员记录
        $projectMemberIdList = model(ProjectMemberModel::class)
            ->join('project on project.id = project_member.project_id')
            ->where(['project.tenant_id' => $tenantId, 'project_member.user_id' => $user['id']])
            ->field('project_member.id')
            ->column('id');
        foreach (array_chunk($projectMemberIdList, 200) as $deleteIdList) {
            model(ProjectMemberModel::class)->where(['id' => ['IN', implode(',', $deleteIdList)]])->delete();
        }
        return true;
    }
}
